package cn.edu.jju.psytest.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import cn.edu.jju.psytest.model.vo.UserVo;
import cn.edu.jju.psytest.web.validator.UserValidator;

@SuppressWarnings("restriction")
@Controller
@SessionAttributes("userVo")
public class LoginController {

	private UserValidator userValidator;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String initForm(ModelMap model) {
		model.addAttribute("userVo", new UserVo());
		return "/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("userVo") UserVo user,
			BindingResult result) {
		userValidator.validate(user, result);
		if (result.hasErrors()) {
			return "login";
		} else {
			return "redirect:/user";
		}
	}

	@RequestMapping("/logout")
	public String logout(SessionStatus status) {
		status.setComplete();
		return "redirect:/login";
	}

	/**
	 * Getters And Setters
	 */
	public UserValidator getUserValidator() {
		return userValidator;
	}

	@Resource
	public void setUserValidator(UserValidator userValidator) {
		this.userValidator = userValidator;
	}
}
